<?php

class m111122_015756_account_category_project extends CDbMigration {
	public function safeUp() {
		$this->dropColumn('erp_account_token_category', 'initialDebit');
		$this->dropColumn('erp_account_token_category', 'initialCredit');
		$this
			->createTable('erp_account_token_project',
				array(
					'id' => 'pk',
					'name' => 'string',
					'note' => 'string',
					'inCompany' => 'boolean',
					'createTime' => 'datetime',
					'createUserId' => 'int',
					'updateTime' => 'datetime',
					'updateUserId' => 'int',
				));
		$this
			->createIndex("account_token_project_create_user_id", 'erp_account_token_project',
				'createUserId');
		$this
			->addForeignKey('fk_account_token_project_create_user_id', 'erp_account_token_project',
				'createUserId', 'erp_user', 'id', 'SET NULL', 'CASCADE');
		$this
			->createIndex("account_token_project_update_user_id", 'erp_account_token_project',
				'updateUserId');
		$this
			->addForeignKey('fk_account_token_project_update_user_id', 'erp_account_token_project',
				'updateUserId', 'erp_user', 'id', 'SET NULL', 'CASCADE');

		//merge data
		$tokens = AccountToken::model()
			->findAll(array(
				'select' => 'projectId',
				'distinct' => true
			));
		$projectIds = array();
		foreach ($tokens as $token) {
			$projectIds[] = $token->projectId;
		}
		$this
			->insert('erp_account_token_project',
				array(
					'id' => 1,
					'name' => '公司账目',
					'inCompany' => true,
				));
		$criteria = new CDbCriteria();
		$criteria->addInCondition('id', $projectIds);
		$existProjects = Project::model()->findAll($criteria);
		foreach ($existProjects as $p) {
			$this
				->insert('erp_account_token_project',
					array(
						'id' => $p->id,
						'name' => $p->name,
						'inCompany' => true,
					));
		}
		$this->dropForeignKey('fk_account_token_project_id', 'erp_account_token');

		$this->execute('update erp_account_token set projectId=1 where projectId is NULL');

		$this
			->addForeignKey('fk_account_token_project_id', 'erp_account_token', 'projectId',
				'erp_account_token_project', 'id', 'SET NULL', 'CASCADE');

	}

	public function safeDown() {
		$this->addColumn('erp_account_token_category', 'initialDebit', 'decimal(16,2)');
		$this->addColumn('erp_account_token_category', 'initialCredit', 'decimal(16,2)');
		$this->dropForeignKey('fk_account_token_project_id', 'erp_account_token');
		$this->execute('update erp_account_token set projectId=null where projectId=1');
		$this
			->addForeignKey('fk_account_token_project_id', 'erp_account_token', 'projectId',
				'erp_project', 'id', 'SET NULL', 'CASCADE');
		$this->dropTable('erp_account_token_project');

	}
}
